﻿using MultiDAQ_Analysis.Util;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace MultiDAQ_Analysis.Util
{
    public class UdpProtocolSender : IDisposable
    {
        private UdpClient udpClient;
        private long totalSentPackets = 0;
        private bool disposed = false;

        public event Action<string> OnLogMessage;
        public event Action<string> OnErrorMessage;
        public event Action<long> OnPacketSent;

        public string TargetIP { get; set; } = AppConfig.UdpRemoteIP.ToString();
        public int TargetPort { get; set; } = AppConfig.UdpRemotePort;

        public long TotalSentPackets => Interlocked.Read(ref totalSentPackets);

        public UdpProtocolSender()
        {
            InitializeClient();
        }

        private void InitializeClient()
        {
            try
            {
                udpClient = new UdpClient();
                udpClient.Client.SendBufferSize = 8 * 1024 * 1024;
                OnLogMessage?.Invoke($"UDP发送客户端初始化完成 - 目标地址: {TargetIP}:{TargetPort}");
            }
            catch (Exception ex)
            {
                OnErrorMessage?.Invoke($"UDP客户端初始化失败: {ex.Message}");
                throw;
            }
        }

        #region 七个寄存器的独立发送方法

        /// <summary>
        /// 0x00 - 发送重启请求
        /// </summary>
        /// <param name="restart">true=重启, false=不重启</param>
        /// <returns>是否发送成功</returns>
        public bool SendRestartRequest(bool restart = true)
        {
            uint value = restart ? 1u : 0u;
            bool success = SendStandardProtocolFrame(0x00, value);

            if (success)
            {
                OnLogMessage?.Invoke($"启动请求发送成功: {(restart ? "启动" : "不启动")}");
            }
            else
            {
                OnErrorMessage?.Invoke("启动请求发送失败");
            }

            return success;
        }

        /// <summary>
        /// 0x01 - 发送通道选择
        /// </summary>
        /// <param name="channelMask">通道掩码，例如0xFF表示所有通道</param>
        /// <returns>是否发送成功</returns>
        public bool SendChannelSelection(uint channelMask)
        {
            bool success = SendStandardProtocolFrame(0x01, channelMask);

            if (success)
            {
                OnLogMessage?.Invoke($"通道选择发送成功: 0x{channelMask:X2} (二进制: {Convert.ToString(channelMask, 2).PadLeft(8, '0')})");
            }
            else
            {
                OnErrorMessage?.Invoke("通道选择发送失败");
            }

            return success;
        }

        /// <summary>
        /// 0x01 - 发送通道选择（通过通道号数组）
        /// </summary>
        /// <param name="enabledChannels">启用的通道号数组，例如 new int[]{1,2,3,4}</param>
        /// <returns>是否发送成功</returns>
        public bool SendChannelSelection(int[] enabledChannels)
        {
            byte channelMask = BuildChannelMask(enabledChannels);
            return SendChannelSelection(channelMask);
        }

        /// <summary>
        /// 0x02 - 发送停止请求
        /// </summary>
        /// <param name="stop">true=停止, false=不停止</param>
        /// <returns>是否发送成功</returns>
        public bool SendStopRequest(bool stop = true)
        {
            uint value = stop ? 1u : 0u;
            bool success = SendStandardProtocolFrame(0x02, value);

            if (success)
            {
                OnLogMessage?.Invoke($"停止请求发送成功: {(stop ? "停止" : "不停止")}");
            }
            else
            {
                OnErrorMessage?.Invoke("停止请求发送失败");
            }

            return success;
        }

        /// <summary>
        /// 0x03 - 发送下限值（按通道）
        /// </summary>
        /// <param name="channel">通道号 (1-3)</param>
        /// <param name="voltage">电压值</param>
        /// <returns>是否发送成功</returns>
        public bool SendLowerLimit(byte channel, double voltage)
        {
            if (!ValidateChannel(channel)) return false;

            uint voltageUint = ConvertVoltageToUint(voltage);
            bool success = SendChannelProtocolFrame(0x03, channel, voltageUint);

            if (success)
            {
                OnLogMessage?.Invoke($"通道{channel}下限值设置成功: {voltage:F4}V");
            }
            else
            {
                OnErrorMessage?.Invoke($"通道{channel}下限值设置失败");
            }

            return success;
        }

        /// <summary>
        /// 0x03 - 批量发送所有通道的下限值
        /// </summary>
        /// <param name="channelVoltages">通道电压字典</param>
        /// <param name="frameInterval">帧间延迟毫秒</param>
        /// <returns>是否全部发送成功</returns>
        public bool SendLowerLimitBatch(Dictionary<byte, double> channelVoltages, int frameInterval = 20)
        {
            return SendVoltageBatch("下限值", 0x03, channelVoltages, frameInterval);
        }

        /// <summary>
        /// 0x04 - 发送低阈值（按通道）
        /// </summary>
        /// <param name="channel">通道号 (1-3)</param>
        /// <param name="voltage">电压值</param>
        /// <returns>是否发送成功</returns>
        public bool SendLowThreshold(byte channel, double voltage)
        {
            if (!ValidateChannel(channel)) return false;

            uint voltageUint = ConvertVoltageToUint(voltage);
            bool success = SendChannelProtocolFrame(0x04, channel, voltageUint);

            if (success)
            {
                OnLogMessage?.Invoke($"通道{channel}低阈值设置成功: {voltage:F4}V");
            }
            else
            {
                OnErrorMessage?.Invoke($"通道{channel}低阈值设置失败");
            }

            return success;
        }

        /// <summary>
        /// 0x04 - 批量发送所有通道的低阈值
        /// </summary>
        /// <param name="channelVoltages">通道电压字典</param>
        /// <param name="frameInterval">帧间延迟毫秒</param>
        /// <returns>是否全部发送成功</returns>
        public bool SendLowThresholdBatch(Dictionary<byte, double> channelVoltages, int frameInterval = 20)
        {
            return SendVoltageBatch("低阈值", 0x04, channelVoltages, frameInterval);
        }

        /// <summary>
        /// 0x05 - 发送高阈值（按通道）
        /// </summary>
        /// <param name="channel">通道号 (1-3)</param>
        /// <param name="voltage">电压值</param>
        /// <returns>是否发送成功</returns>
        public bool SendHighThreshold(byte channel, double voltage)
        {
            if (!ValidateChannel(channel)) return false;

            uint voltageUint = ConvertVoltageToUint(voltage);
            bool success = SendChannelProtocolFrame(0x05, channel, voltageUint);

            if (success)
            {
                OnLogMessage?.Invoke($"通道{channel}高阈值设置成功: {voltage:F4}V");
            }
            else
            {
                OnErrorMessage?.Invoke($"通道{channel}高阈值设置失败");
            }

            return success;
        }

        /// <summary>
        /// 0x05 - 批量发送所有通道的高阈值
        /// </summary>
        /// <param name="channelVoltages">通道电压字典</param>
        /// <param name="frameInterval">帧间延迟毫秒</param>
        /// <returns>是否全部发送成功</returns>
        public bool SendHighThresholdBatch(Dictionary<byte, double> channelVoltages, int frameInterval = 20)
        {
            return SendVoltageBatch("高阈值", 0x05, channelVoltages, frameInterval);
        }

        /// <summary>
        /// 0x06 - 发送间隔点数
        /// </summary>
        /// <param name="points">间隔点数</param>
        /// <returns>是否发送成功</returns>
        public bool SendSpacedPoints(uint points)
        {
            bool success = SendStandardProtocolFrame(0x06, points);

            if (success)
            {
                OnLogMessage?.Invoke($"间隔点数设置成功: {points}");
            }
            else
            {
                OnErrorMessage?.Invoke("间隔点数设置失败");
            }

            return success;
        }

        #endregion


        #region 时间谱脉宽测试相关寄存器（0x08-0x0A）

        /// <summary>
        /// 0x08 - 发送时间谱脉宽起始阈值（按通道）
        /// </summary>
        /// <param name="channel">通道号 (1-8)</param>
        /// <param name="voltage">阈值电压（-1.75V ~ +1.75V）</param>
        /// <returns>是否发送成功</returns>
        public bool SendPulseWidthStartThreshold(byte channel, double voltage)
        {
            if (!ValidateChannel(channel)) return false;

            if (voltage < -1.75 || voltage > 1.75)
            {
                OnErrorMessage?.Invoke($"通道{channel}脉宽起始阈值超出范围: {voltage:F4}V，允许范围: -1.75V ~ +1.75V");
                return false;
            }

            uint voltageUint = ConvertVoltageToUint(voltage);
            bool success = SendChannelProtocolFrame(0x08, channel, voltageUint);

            if (success)
            {
                OnLogMessage?.Invoke($"通道{channel}时间谱脉宽起始阈值设置成功: {voltage:F4}V");
            }
            else
            {
                OnErrorMessage?.Invoke($"通道{channel}时间谱脉宽起始阈值设置失败");
            }

            return success;
        }

        /// <summary>
        /// 0x08 - 批量发送所有通道的脉宽起始阈值
        /// </summary>
        /// <param name="channelVoltages">通道电压字典，例如: {{1, 0.5}, {2, 0.6}, {3, 0.7}}</param>
        /// <param name="frameInterval">帧间延迟毫秒</param>
        /// <returns>是否全部发送成功</returns>
        public bool SendPulseWidthStartThresholdBatch(Dictionary<byte, double> channelVoltages, int frameInterval = 20)
        {
            return SendVoltageBatch("脉宽起始阈值", 0x08, channelVoltages, frameInterval);
        }

        /// <summary>
        /// 0x09 - 发送时间谱脉宽测试时间（通过时间自动转换为采样点数）
        /// </summary>
        /// <param name="timeNs">测试时间（纳秒 ns）</param>
        /// <returns>是否发送成功</returns>
        public bool SendPulseWidthTestTime(double timeNs)
        {
            // 采样率固定为250MHz，即每个采样点间隔4ns
            // 采样点数 = 时间(ns) / 4
            uint samplingPoints = (uint)Math.Round(timeNs / 4.0);

            bool success = SendStandardProtocolFrame(0x09, samplingPoints);

            if (success)
            {
                double timeUs = timeNs / 1000.0;      // 转换为微秒
                double timeMs = timeNs / 1000000.0;   // 转换为毫秒
                OnLogMessage?.Invoke($"时间谱脉宽测试时间设置成功: {timeNs:F2} ns ({timeUs:F2} μs / {timeMs:F4} ms) → 采样点数: {samplingPoints}");
            }
            else
            {
                OnErrorMessage?.Invoke("时间谱脉宽测试时间设置失败");
            }

            return success;
        }

        /// <summary>
        /// 0x0A - 发送时间谱脉宽测试启动请求
        /// </summary>
        /// <param name="start">true=启动测试, false=停止测试</param>
        /// <returns>是否发送成功</returns>
        public bool SendPulseWidthTestStartRequest(bool start = true)
        {
            uint value = start ? 1u : 0u;
            bool success = SendStandardProtocolFrame(0x0A, value);

            if (success)
            {
                OnLogMessage?.Invoke($"时间谱脉宽测试{(start ? "启动" : "停止")}请求发送成功");
            }
            else
            {
                OnErrorMessage?.Invoke("时间谱脉宽测试启动请求发送失败");
            }

            return success;
        }


        #endregion

 

        #region 便捷的组合方法

        /// <summary>
        /// 快速启动系统（发送通道选择 + 重启请求）
        /// </summary>
        /// <param name="enabledChannels">启用的通道数组</param>
        /// <param name="frameInterval">帧间延迟毫秒</param>
        /// <returns>是否发送成功</returns>
        public bool QuickStart(int[] enabledChannels, int frameInterval = 20)
        {
            try
            {
                OnLogMessage?.Invoke("快速启动系统...");

                // 1. 发送通道选择
                if (!SendChannelSelection(enabledChannels))
                {
                    return false;
                }
                Thread.Sleep(frameInterval);

                // 2. 发送重启请求
                if (!SendRestartRequest(true))
                {
                    return false;
                }

                OnLogMessage?.Invoke("系统启动完成");
                return true;
            }
            catch (Exception ex)
            {
                OnErrorMessage?.Invoke($"快速启动失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 快速停止系统
        /// </summary>
        /// <returns>是否发送成功</returns>
        public bool QuickStop()
        {
            try
            {
                OnLogMessage?.Invoke("快速停止系统...");

                bool success = SendStopRequest(true);

                if (success)
                {
                    OnLogMessage?.Invoke("系统停止完成");
                }

                return success;
            }
            catch (Exception ex)
            {
                OnErrorMessage?.Invoke($"快速停止失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 完整配置系统（发送所有七个寄存器的数据）
        /// </summary>
        /// <param name="config">完整配置对象</param>
        /// <returns>是否全部发送成功</returns>
        public bool ConfigureSystem(SystemConfiguration config)
        {
            try
            {
                OnLogMessage?.Invoke("开始完整配置系统...");

                int interval = config.FrameInterval;

                // 1. 通道选择
                if (!SendChannelSelection(config.EnabledChannels))
                    return false;
                Thread.Sleep(interval);

                // 2. 重启请求
                if (!SendRestartRequest(config.AutoStart))
                    return false;
                Thread.Sleep(interval);

                // 3. 停止请求（通常为false）
                if (!SendStopRequest(false))
                    return false;
                Thread.Sleep(interval);

                // 4. 批量发送下限值
                if (config.ChannelLowerLimits?.Count > 0)
                {
                    if (!SendLowerLimitBatch(config.ChannelLowerLimits, interval))
                        return false;
                }

                // 5. 批量发送低阈值
                if (config.ChannelLowThresholds?.Count > 0)
                {
                    if (!SendLowThresholdBatch(config.ChannelLowThresholds, interval))
                        return false;
                }

                // 6. 批量发送高阈值
                if (config.ChannelHighThresholds?.Count > 0)
                {
                    if (!SendHighThresholdBatch(config.ChannelHighThresholds, interval))
                        return false;
                }

                // 7. 间隔点数
                if (!SendSpacedPoints(config.SpacedPoints))
                    return false;

                OnLogMessage?.Invoke("系统配置完成");
                return true;
            }
            catch (Exception ex)
            {
                OnErrorMessage?.Invoke($"系统配置失败: {ex.Message}");
                return false;
            }
        }

        #endregion

        #region 私有辅助方法

        private bool SendStandardProtocolFrame(byte regAddr, uint dataValue)
        {
            try
            {
                byte[] frame = MakeStandardProtocolFrame(regAddr, dataValue);
                udpClient.Send(frame, frame.Length, TargetIP, TargetPort);

                long newCount = Interlocked.Increment(ref totalSentPackets);
                OnPacketSent?.Invoke(newCount);

                string hexString = BitConverter.ToString(frame).Replace("-", " ");

                OnLogMessage?.Invoke($"发送标准协议帧成功:{hexString}");
                return true;
            }
            catch (Exception ex)
            {
                OnErrorMessage?.Invoke($"发送标准协议帧失败: {ex.Message}");
                return false;
            }
        }

        private bool SendChannelProtocolFrame(byte regAddr, byte channel, uint dataValue)
        {
            try
            {
                byte[] frame = MakeChannelProtocolFrame(regAddr, channel, dataValue);
                udpClient.Send(frame, frame.Length, TargetIP, TargetPort);
                long newCount = Interlocked.Increment(ref totalSentPackets);
                OnPacketSent?.Invoke(newCount);

                // 修改这一行，将字节数组转换为十六进制字符串
                string hexString = BitConverter.ToString(frame).Replace("-", " ");
                OnLogMessage?.Invoke($"发送标准协议帧成功: {hexString}");

                return true;
            }
            catch (Exception ex)
            {
                OnErrorMessage?.Invoke($"发送通道协议帧失败: {ex.Message}");
                return false;
            }
        }

        private bool SendVoltageBatch(string typeName, byte regAddr, Dictionary<byte, double> channelVoltages, int frameInterval)
        {
            try
            {
                OnLogMessage?.Invoke($"开始批量发送{typeName}...");

                bool allSuccess = true;
                foreach (var kvp in channelVoltages)
                {
                    if (!ValidateChannel(kvp.Key))
                    {
                        allSuccess = false;
                        continue;
                    }

                    uint voltageUint = ConvertVoltageToUint(kvp.Value);
                    if (!SendChannelProtocolFrame(regAddr, kvp.Key, voltageUint))
                    {
                        allSuccess = false;
                        OnErrorMessage?.Invoke($"通道{kvp.Key}{typeName}发送失败");
                    }

                    if (frameInterval > 0)
                        Thread.Sleep(frameInterval);
                }

                OnLogMessage?.Invoke($"批量发送{typeName}完成，成功: {allSuccess}");
                return allSuccess;
            }
            catch (Exception ex)
            {
                OnErrorMessage?.Invoke($"批量发送{typeName}失败: {ex.Message}");
                return false;
            }
        }

        private bool ValidateChannel(byte channel)
        {
            if (channel < 1 || channel > 8)
            {
                OnErrorMessage?.Invoke($"通道号无效: {channel}，必须在1-8范围内");
                return false;
            }
            return true;
        }

        private byte BuildChannelMask(int[] enabledChannels)
        {
            if (enabledChannels == null || enabledChannels.Length == 0)
                return 0;

            byte mask = 0;
            foreach (int channel in enabledChannels)
            {
                if (channel >= 1 && channel <= 8)
                {
                    mask |= (byte)(1 << (channel - 1));
                }
            }
            return mask;
        }

        //// 1. 修改电压转换函数 - 匹配2字节0-3V规范
        //private uint ConvertVoltageToUint(double voltage)
        //{
        //    // 14位ADC: 0V→0, 3V→16384
        //    return (uint)Math.Round(Math.Abs(voltage) * 16384.0 / 3.0);
        //}

        private uint ConvertVoltageToUint(double voltage)
        {
            if (voltage < -1.75 || voltage > 1.75)
            {
                throw new ArgumentOutOfRangeException(nameof(voltage),
                    "电压必须在-1.75V到+1.75V范围内");
            }

            uint result = (uint)Math.Round((voltage + 1.75) * 16384.0 / 3.5);
            return Math.Min(result, 16383u);
        }
        // 制作标准协议帧（用于0x00, 0x01, 0x02, 0x06）
        private static byte[] MakeStandardProtocolFrame(byte regAddr, uint data)
        {
            return new byte[]
            {
                0x55, 0xA5, regAddr,
                (byte)((data >> 24) & 0xFF), (byte)((data >> 16) & 0xFF),
                (byte)((data >> 8) & 0xFF), (byte)(data & 0xFF), 0xF0
            };
        }



        // 2. 修改通道协议帧构造 - 8字节格式，2字节有效数据
        private static byte[] MakeChannelProtocolFrame(byte regAddr, byte channel, uint data)
        {
            return new byte[]
            {
        0x55, 0xA5, regAddr, channel,           // 4字节：帧头+寄存器+通道
        0x00,                                   // 1字节：补零
        (byte)((data >> 8) & 0xFF),             // 1字节：数据高位
        (byte)(data & 0xFF),                    // 1字节：数据低位
        0xF0                                    // 1字节：帧尾
            };
            // 总计：8字节
        }

        /* 
        帧格式说明（8字节）：
        [0] 0x55 - 帧头1
        [1] 0xA5 - 帧头2  
        [2] regAddr - 寄存器地址（0x03/0x04/0x05）
        [3] channel - 通道号（1-8）
        [4] data_byte2 - 数据字节2（高位）
        [5] data_byte1 - 数据字节1（中位）
        [6] data_byte0 - 数据字节0（低位）
        [7] 0xF0 - 帧尾

        示例：
        电压1.5V -> 15000 (0x003A98) -> 3字节：00 3A 98
        帧数据：55 A5 05 02 00 3A 98 F0
                ↑  ↑  ↑  ↑  ↑  ↑  ↑  ↑
               头1 头2 寄存 通道 高位 中位 低位 尾

        当前你的转换函数ConvertVoltageToUint返回的是uint，
        可以完美支持3字节数据（最大值16777215）
        */

        private string BytesToHexString(byte[] bytes)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.AppendFormat("{0:X2}", bytes[i]);
                if (i < bytes.Length - 1) sb.Append(" ");
            }
            return sb.ToString();
        }

        #endregion

        #region 原有方法（保持兼容性）

        public bool SendRawData(byte[] data, bool appendCRC = false)
        {
            try
            {
                if (data == null || data.Length == 0)
                {
                    OnErrorMessage?.Invoke("发送数据不能为空");
                    return false;
                }

                byte[] payload;
                if (appendCRC)
                {
                    uint crc = CRC32.Compute(data);
                    byte[] crcBytes = BitConverter.GetBytes(crc);
                    payload = new byte[data.Length + 4];
                    Buffer.BlockCopy(data, 0, payload, 0, data.Length);
                    Buffer.BlockCopy(crcBytes, 0, payload, data.Length, 4);

                    OnLogMessage?.Invoke($"发送原始数据+CRC → {TargetIP}:{TargetPort} - {BytesToHexString(data)} + CRC32={BytesToHexString(crcBytes)}");
                }
                else
                {
                    payload = data;
                    OnLogMessage?.Invoke($"发送原始数据 → {TargetIP}:{TargetPort} - {BytesToHexString(payload)}");
                }

                udpClient.Send(payload, payload.Length, TargetIP, TargetPort);

                long newCount = Interlocked.Increment(ref totalSentPackets);
                OnPacketSent?.Invoke(newCount);

                return true;
            }
            catch (Exception ex)
            {
                OnErrorMessage?.Invoke($"发送原始数据失败: {ex.Message}");
                return false;
            }
        }

        public void ResetCounter()
        {
            Interlocked.Exchange(ref totalSentPackets, 0);
        }

        #endregion



        #region 发送DAC模块设置 
        /// <summary>
        /// 0x07 - 发送DAC模块设置
        /// </summary>
        /// <param name="voltage">输出电压值（-9.99V ~ +9.99V，0V用于校准）</param>
        /// <returns>是否发送成功</returns>
        public bool SendDACSet(double voltage)
        {
            // 验证电压范围
            if (Math.Abs(voltage) > 9.99)
            {
                OnErrorMessage?.Invoke($"DAC电压值超出范围: {voltage:F2}V，允许范围: -9.99V ~ +9.99V");
                return false;
            }

            try
            {
                byte[] dacData = ConvertVoltageToDACBytes(voltage);
                byte[] frame = MakeDACProtocolFrame(dacData);
                udpClient.Send(frame, frame.Length, TargetIP, TargetPort);

                long newCount = Interlocked.Increment(ref totalSentPackets);
                OnPacketSent?.Invoke(newCount);

                string hexString = BitConverter.ToString(frame).Replace("-", " ");
                string polarityDesc = voltage > 0 ? "正" : voltage < 0 ? "负" : "零";

                OnLogMessage?.Invoke($"DAC设置发送成功: {voltage:F2}V ({polarityDesc}电压) - {hexString}");
                return true;
            }
            catch (Exception ex)
            {
                OnErrorMessage?.Invoke($"DAC设置发送失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 将电压值转换为DAC的5字节数据
        /// </summary>
        /// <param name="voltage">电压值</param>
        /// <returns>5字节DAC数据：[数据头][极性][个位][小数][数据尾]</returns>
        private byte[] ConvertVoltageToDACBytes(double voltage)
        {
            byte[] dacBytes = new byte[5];

            // 数据头固定为0x5A
            dacBytes[0] = 0x5A;

            // 确定极性字节
            if (voltage == 0.0)
            {
                dacBytes[1] = 0x00; // 0V校准
            }
            else if (voltage > 0)
            {
                dacBytes[1] = 0x01; // 正电压
            }
            else
            {
                dacBytes[1] = 0x02; // 负电压
            }

            // 使用绝对值计算数值
            double absVoltage = Math.Abs(voltage);

            // 分离整数和小数部分
            int integerPart = (int)absVoltage;  // 个位数 (0-9)
            int decimalPart = (int)Math.Round((absVoltage - integerPart) * 100); // 小数部分 (00-99)

            // 确保范围有效
            integerPart = Math.Min(9, Math.Max(0, integerPart));
            decimalPart = Math.Min(99, Math.Max(0, decimalPart));

            // 转换为BCD格式
            dacBytes[2] = (byte)(0x00 + integerPart);  // 个位数字节（高位始终为0）
            dacBytes[3] = (byte)((decimalPart / 10) * 16 + (decimalPart % 10)); // 小数字节（BCD格式）

            // 数据尾固定为0xA5
            dacBytes[4] = 0xA5;

            return dacBytes;
        }

        /// <summary>
        /// 制作DAC协议帧
        /// </summary>
        /// <param name="dacData">5字节DAC数据</param>
        /// <returns>完整的8字节协议帧</returns>
        private static byte[] MakeDACProtocolFrame(byte[] dacData)
        {
            if (dacData == null || dacData.Length != 5)
                throw new ArgumentException("DAC数据必须为5字节");

            return new byte[]
            {
        0x55, 0xA5, 0x07,           // 标准帧头 + 寄存器地址
        dacData[0],                 // 数据头 0x5A
        dacData[1],                 // 极性字节
        dacData[2],                 // 个位数字节
        dacData[3],                 // 小数字节
        dacData[4]                  // 数据尾 0xA5
            };
            // 总计：8字节
        }

        #endregion
        public void Dispose()
        {
            if (!disposed)
            {
                udpClient?.Close();
                udpClient?.Dispose();
                disposed = true;
                OnLogMessage?.Invoke("UDP发送客户端已释放");
            }
        }
    }

    /// <summary>
    /// 系统配置类
    /// </summary>
    public class SystemConfiguration
    {
        public int[] EnabledChannels { get; set; } = { 1, 2, 3 };
        public bool AutoStart { get; set; } = true;
        public Dictionary<byte, double> ChannelLowerLimits { get; set; } = new Dictionary<byte, double>();
        public Dictionary<byte, double> ChannelLowThresholds { get; set; } = new Dictionary<byte, double>();
        public Dictionary<byte, double> ChannelHighThresholds { get; set; } = new Dictionary<byte, double>();
        public uint SpacedPoints { get; set; } = 100;
        public int FrameInterval { get; set; } = 20;

        /// <summary>
        /// 创建默认配置
        /// </summary>
        public static SystemConfiguration CreateDefault()
        {
            return new SystemConfiguration
            {
                EnabledChannels = new int[] { 1, 2, 3 },
                AutoStart = true,
                ChannelLowerLimits = new Dictionary<byte, double> { { 1, 1.0 }, { 2, 1.0 }, { 3, 1.0 } },
                ChannelLowThresholds = new Dictionary<byte, double> { { 1, 2.0 }, { 2, 2.0 }, { 3, 2.0 } },
                ChannelHighThresholds = new Dictionary<byte, double> { { 1, 3.0 }, { 2, 3.0 }, { 3, 3.0 } },
                SpacedPoints = 100,
                FrameInterval = 20
            };
        }
    }
}
